package com.efounder.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.builder.base.data.ESPRowSet;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.email.activity.EmailInBoxAct;
import com.efounder.email.activity.EmailOutBoxAct;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.ospmobilelib.R;
import com.efounder.util.CommonPo;
import com.efounder.util.GetTokenDataByPO;
import com.efounder.util.GlobalMap;
import com.jauker.widget.BadgeView;
import com.pansoft.resmanager.ResFileManager;
import com.pansoft.xmlparse.OptionParser;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

/**
 * 邮箱首页
 *
 * @author yqs
 */
public class EmailMainFragment extends BaseFragment {

	private static final String TAG = "EmailMainFragment";

	// private RelativeLayout inboxLayout;// 收件箱
	// private RelativeLayout outboxLayout;// 发件箱
	// private LinearLayout bodyLayout;
	// private LayoutInflater inflater;
	private View rootView;
	private String names[];
	private String types[];
	private String boxTypes[];
	private String icons[];
	private String dpCount = "0";// 总部邮箱未读邮件条数
	private String pgCount = "0";// 普光邮箱未读邮件条数
	private ListView listView;
	private ListAdapter listAdapter;
	private List<Map<String, String>> listMap;
	private static final String PATH = ResFileManager.IMAGE_DIR
			+ File.separator;

	private AsyncTask<Void, Void, String> asyncTask;

	public EmailMainFragment() {
		super();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.activity_email_homepage,
				container, false);
		listMap = new ArrayList<Map<String, String>>();
		initView();
		initData();
		return rootView;
	}

	private void initView() {

		RelativeLayout include = (RelativeLayout) rootView
				.findViewById(R.id.include);
		include.setVisibility(View.VISIBLE);
		LinearLayout leftbacklayout = (LinearLayout) rootView
				.findViewById(R.id.leftbacklayout);
		leftbacklayout.setVisibility(View.VISIBLE);
		TextView title = (TextView) rootView.findViewById(R.id.fragmenttitle);
		leftbacklayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getActivity().finish();
			}
		});
		title.setText("邮箱");
		// bodyLayout = (LinearLayout) rootView.findViewById(R.id.body);
		listView = (ListView) rootView
				.findViewById(R.id.email_fragment_listview);
		// inflater = getActivity().getLayoutInflater();
		if (isAlone()) {
			include.setVisibility(View.VISIBLE);
		} else {
			include.setVisibility(View.GONE);
		}
	}

	private void initData() {

		Map<String, String> emailMap = OptionParser.getInstance()
				.getElementById("email");
		names = emailMap.get("list").split(";");
		types = emailMap.get("type").split(";");
		boxTypes = emailMap.get("boxtype").split(";");
		icons = emailMap.get("icon").split(";");

		for (int i = 0; i < names.length; i++) {
			Map<String, String> itemMap = new HashMap<String, String>();
			String emailName = names[i];
			String type = types[i];
			String boxType = boxTypes[i];
			String icon = PATH + icons[i];
			itemMap.put("emailName", emailName);
			itemMap.put("type", type);
			itemMap.put("boxType", boxType);
			itemMap.put("icon", icon);
			itemMap.put("num", "0");
			listMap.add(itemMap);

		}
		listAdapter = new ListAdapter();
		listView.setAdapter(listAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				String type = listMap.get(position).get("type");
				String boxType = listMap.get(position).get("boxType");
				if ("EmailOutBox".equals(boxType)) {
					Intent intent = new Intent(getActivity(),
							EmailOutBoxAct.class);
					intent.putExtra("emailtype", type);
					intent.putExtra("boxtype", boxType);
					startActivity(intent);
				} else if ("EmailInbox".equals(boxType)) {
					Intent intent = new Intent(getActivity(),
							EmailInBoxAct.class);
					intent.putExtra("emailtype", type);
					intent.putExtra("boxtype", boxType);
					startActivity(intent);
				}

			}
		});

		//  loadDataByNet();

	}

	@Override
	public void onResume() {
		super.onResume();

		// 重新获取未读邮件数量
		loadDataByNet();

	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (asyncTask != null) {
			asyncTask.cancel(true);
		}
	}

	/**
	 * 通过网络 加载数据
	 */
	private void loadDataByNet() {
		System.out.println("加载未读邮件数量");
		if (asyncTask != null) {
			asyncTask.cancel(true);
		}
		asyncTask = new AsyncTask<Void, Void, String>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// LoadingDataUtilBlack.show(getActivity());
			}

			@Override
			protected String doInBackground(Void... params) {
				String pgToken = GlobalMap.getProperty(
						"EMAILTokenId", "");
				String dpToken = GlobalMap.getProperty(
						"DPEMAILTokenId", "");
				long time = System.currentTimeMillis();
				if (pgToken.equals("")) {
					GetTokenDataByPO.getEmailTokenid("EMAIL");
				}
				if (dpToken.equals("")) {
					GetTokenDataByPO.getEmailTokenid("DPEMAIL");
				}

				getEmailCount();
				System.out.println("---请求邮箱token和未读数量所需时间--"
						+ (System.currentTimeMillis() - time));
				return dpCount;
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);

				//   LoadingDataUtilBlack.dismiss();
				listMap.get(0).put("num", dpCount);
				listMap.get(2).put("num", pgCount);
				listAdapter.notifyDataSetChanged();
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
			}

		};
		asyncTask.executeOnExecutor(Executors.newCachedThreadPool());

	}

	// 获取邮件未读数量
	private void getEmailCount() {
		// 创建PO

		JParamObject PO = JParamObject.Create();
		CommonPo.setPoToNull();
		JResponseObject RO = null;
		String pgToken = GlobalMap.getProperty("EMAILTokenId", "");
		String dpToken = GlobalMap.getProperty("DPEMAILTokenId", "");

		if (pgToken.equals("") && !dpToken.equals("")) {
			PO.SetValueByParamName("WB_SYS_KEY", "DPEMAIL");
			PO.SetValueByParamName("DPEMAIL_systemmethod", "EmailCount");
			PO.SetValueByParamName("DPEMAIL_params_tokenIDFromMoblie", dpToken);

		} else if (!pgToken.equals("") && dpToken.equals("")) {
			PO.SetValueByParamName("WB_SYS_KEY", "EMAIL");
			PO.SetValueByParamName("EMAIL_systemmethod", "EmailCount");
			PO.SetValueByParamName("EMAIL_params_tokenIDFromMoblie", pgToken);
		} else if (!pgToken.equals("") && !dpToken.equals("")) {
			PO.SetValueByParamName("WB_SYS_KEY", "EMAIL,DPEMAIL");
			PO.SetValueByParamName("EMAIL_systemmethod", "EmailCount");
			PO.SetValueByParamName("EMAIL_params_tokenIDFromMoblie", pgToken);
			PO.SetValueByParamName("DPEMAIL_systemmethod", "EmailCount");
			PO.SetValueByParamName("DPEMAIL_params_tokenIDFromMoblie", dpToken);
		}

		try {
			// 连接服务器
			RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (RO != null) {
			@SuppressWarnings("unchecked")
			HashMap<String, Object> map = (HashMap<String, Object>) RO
					.getResponseMap();

			if (map.containsKey("EMAIL")) {
				EFDataSet numDataSet = (EFDataSet) map.get("EMAIL");
				List<ESPRowSet> numRowSets = numDataSet.getRowSetList();
				if (numRowSets != null) {

					EFRowSet efORowSet = (EFRowSet) numRowSets.get(0);
					String count = (String) efORowSet.getDataMap().get("sjx");
					pgCount = count;

				}

			}
			if (map.containsKey("DPEMAIL")) {
				EFDataSet numDataSet = (EFDataSet) map.get("DPEMAIL");
				List<ESPRowSet> numRowSets = numDataSet.getRowSetList();
				if (numRowSets != null) {
					EFRowSet efORowSet = (EFRowSet) numRowSets.get(0);
					String count = (String) efORowSet.getDataMap().get("sjx");
					dpCount = count;
					Log.i("EmailMainFragment", "dpCount:" + count);
				}

			}
		}
	}

	/**
	 * listview 适配器
	 *
	 * @author yqs
	 */
	private class ListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return listMap.size();
		}

		@Override
		public Map<String, String> getItem(int position) {
			return listMap.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			Map<String, String> itemMap = listMap.get(position);
			if (convertView == null) {
				convertView = LayoutInflater.from(getActivity()).inflate(
						R.layout.email_main_item, null);
				holder = new ViewHolder();
				holder.titleTextView = (TextView) convertView
						.findViewById(R.id.textView1);
				holder.iconIView = (ImageView) convertView
						.findViewById(R.id.acticity_inbox);
				holder.badgeView = new BadgeView(getActivity());
				holder.badgeView.setBadgeGravity(Gravity.TOP | Gravity.RIGHT);
				holder.badgeView.setTargetView(holder.iconIView);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();

			}

			holder.titleTextView.setText(itemMap.get("emailName"));
			Bitmap bm = BitmapFactory.decodeFile(itemMap.get("icon"));
			holder.iconIView.setImageBitmap(bm);
			if (itemMap.get("num").equals("0") || itemMap.get("num") == null) {
				holder.badgeView.setVisibility(View.GONE);
			} else {
				holder.badgeView.setBadgeCount(Integer.valueOf(itemMap
						.get("num")));
			}

			return convertView;
		}

	}

	class ViewHolder {
		TextView titleTextView;
		ImageView iconIView;
		BadgeView badgeView;
	}

	// /**
	// * 得到 token
	// *
	// * @return
	// */
	// @SuppressWarnings({ "unused", "unchecked" })
	// private void getTokenID() {
	// // 创建PO
	//
	// JParamObject PO = JParamObject.Create();
	// CommonPo.setPoToNull();
	// JResponseObject RO = null;
	// EFDataSet tokenEmailDataSet = null;
	//
	// String usereId = AndroidGlobalMap.getUserID();
	// String password = AndroidGlobalMap.getPassword();
	// for (int i = 0; i < types.length; i = i + 2) {
	//
	// }
	// PO.SetValueByParamName("WB_SYS_KEY", "DPEMAIL,EMAIL");
	// // PO.SetValueByParamName("EMAIL_params_Userid", "fengjsh.zyyt");
	// // PO.SetValueByParamName("EMAIL_params_Pwd", "@@@nana110");
	// PO.SetValueByParamName("EMAIL_params_Userid", usereId);
	// PO.SetValueByParamName("EMAIL_params_Pwd", password);
	// PO.SetValueByParamName("EMAIL_systemmethod", "GetTokenID");
	//
	// PO.SetValueByParamName("DPEMAIL_params_Userid", usereId);
	// PO.SetValueByParamName("DPEMAIL_params_Pwd", password);
	// PO.SetValueByParamName("DPEMAIL_systemmethod", "GetTokenID");
	//
	// try {
	// // 连接服务器
	// RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// if (RO != null) {
	// HashMap<String, Object> map = (HashMap<String, Object>) RO
	// .getResponseMap();
	// if (map.containsKey("EMAIL")) {
	// tokenEmailDataSet = (EFDataSet) map.get("EMAIL");// 普光邮箱 token
	// List<ESPRowSet> EmailrowSets = tokenEmailDataSet
	// .getRowSetList();
	// if (EmailrowSets != null) {
	//
	// EFRowSet efORowSet = (EFRowSet) EmailrowSets.get(0);
	// String EmailTokenId = (String) efORowSet.getDataMap().get(
	// "TokenID");
	// System.out.println(EmailTokenId);
	// Log.i(TAG, "普光邮箱tokenid:" + EmailTokenId);
	// GlobalMap.setProperty("EMAILTokenId",
	// EmailTokenId);
	// } else {
	// Log.i(TAG, "普光邮箱tokenid:" + "普光邮箱tokenid不存在");
	// }
	// EFDataSet HeadOfficeDataSet = (EFDataSet) map.get("DPEMAIL");// 总部邮箱token
	// List<ESPRowSet> DPEmailrowSets = HeadOfficeDataSet
	// .getRowSetList();
	// if (DPEmailrowSets != null) {
	//
	// EFRowSet DPefORowSet = (EFRowSet) DPEmailrowSets.get(0);
	// String DPEmailTokenId = (String) DPefORowSet.getDataMap()
	// .get("TokenID");
	// Log.i(TAG, "总部邮箱tokenid:" + DPEmailTokenId);
	//
	// GlobalMap.setProperty("DPEMAILTokenId",
	// DPEmailTokenId);
	//
	// }
	//
	// }
	// }
	//
	// }
}
